const express = require('express')
const router = express.Router()
const path = require('path')
const fs = require('fs')
const multer = require('multer')
const fileDest = path.join(__dirname, '../static/file')
const chunkDest = path.join(__dirname, '../static/chunk')

const fileStorage = multer.diskStorage({
  destination (req, file, cb) {
    cb(null, fileDest)
  },
  filename (req, file, cb) {
    cb(null, file.originalname)
  }
})
const uploadNormal = multer({ storage: fileStorage })

router.post('/normal', uploadNormal.single('file'), (req, res) => {
  // res.send('Hello World!')
  // console.log(req.file)
  const file = req.file
  res.json({
    url: `http://localhost:3000/file/${file.filename}`
  })
})

router.get('/chunk_already', (req, res) => {
  const { hash } = req.query
  const dir = `${chunkDest}/${hash}`
  let fileList = []
  try {
    fileList = fs.readdirSync(dir)
    fileList = fileList.sort((a, b) => {
      const reg = /_(\d+)/
      return reg.exec(a)[1] - reg.exec(b)[1]
    })
    res.json(fileList)
  } catch (err) {
    res.json(fileList)
  }
})

const chunkStorage = multer.diskStorage({
  destination (req, file, cb) {
    const { hash } = req.body
    const dest = `${chunkDest}/${hash}`
    fs.mkdirSync(dest, { recursive: true })
    cb(null, dest)
  },
  filename (req, file, cb) {
    cb(null, file.originalname)
  }
})
const uploadChunk = multer({ storage: chunkStorage })

router.post('/chunk', uploadChunk.single('file'), (req, res) => {
  const { hash } = req.body
  const file = req.file
  res.json(Object.assign(file, { hash }))
})

router.post('/merge', uploadChunk.none(), (req, res) => {
  const { hash, count } = req.body
  const dir = `${chunkDest}/${hash}`
  const fileList = fs.readdirSync(dir)
  if (fileList.length < count) {
    res.end('the slice has not been uploaded')
  }
  let suffix = null
  fileList.sort((a, b) => {
    const reg = /_(\d+)/
    return reg.exec(a)[1] - reg.exec(b)[1]
  }).forEach(item => {
    !suffix ? suffix = /\.([0-9a-zA-Z]+)$/.exec(item)[1] : null
    fs.appendFileSync(`${fileDest}/${hash}.${suffix}`, fs.readFileSync(`${dir}/${item}`))
    fs.unlinkSync(`${dir}/${item}`)
  })
  fs.rmdirSync(dir)
  const filename = `${hash}.${suffix}`
  res.json({
    url:  `http://localhost:3000/file/${filename}`
  })
})

module.exports = router
